<template>
    <div class="chart-container" style="position: relative; width: 100%">
        <!-- <component :is="chartName" :chartData="chartData" :chartStyle="chartStyle"></component> -->
        <compChart
            :chartData="chartData"
            :chartStyle="chartStyle"
            :switchDataMap="switchDataMap"
            theme="walden"
        ></compChart>
        <Spin v-if="loading" fix></Spin>
    </div>
</template>

<script>
import compChart from "@components/templates/chart/chart";
export default {
    props: ["chartType", "requestData", "chartStyle", "stackLabelMap", "handleData", "ajaxRequest"],
    components: {
        compChart,
    },
    data() {
        return {
            isAutoAjax: false,
            loading: false,
            ajaxData: {},
            chartData: {},
            switchDataMap: [],
        };
    },
    watch: {
        requestData: {
            deep: true,
            immediate: true,
            handler(requestData) {
                if (!requestData) return;
                this.renderChart(requestData);
            },
        },
    },
    // async created() {
    //     renderChart();
    // },
    computed: {
        getChartTypeMap() {
            return {
                line: {
                    chartType: "line",
                },
                pie: {
                    chartType: "pie",
                },
                stackBar: {
                    chartType: "stackBar",
                },
            };
        },
    },
    methods: {
        async renderChart(requestData) {
            if (!requestData.component_id || !requestData.start_at) return;
            let { component_id, ...resultData } = {
                ...requestData,
            };
            this.loading = true;
            await this.ajaxRequest({
                component_id: component_id,
                args: JSON.stringify(resultData),
            }).then(
                (res) => {
                    // console.log('chartData', res.data);
                    this.ajaxData = res.data;
                    // let chartTypeData = this.getChartTypeMap[this.chartType];
                    if (this.handleData && typeof this.handleData == 'function') {
                        this.chartData = this.handleData(res.data);
                    }
                    else {
                        this.chartData = this.handleAjaxData(
                            res.data,
                            this.chartType
                        );
                    }
                },
                (err) => {
                    this.$Message.error(err.message);
                }
            );
            this.loading = false;
        },
        // 根据图表类型处理接口数据
        handleAjaxData(ajaxData, chartType) {
            let chartData = {};
            switch (chartType) {
                // 折线图
                case "line":
                    {
                        chartData = this.handleLineData(ajaxData);
                    }
                    break;
                // 饼图
                case "pie":
                    {
                        chartData = this.handlePieData(ajaxData);
                    }
                    break;
                // 堆叠柱状图
                case "stackBar":
                    {
                        chartData = this.handleStackBarData(ajaxData);
                    }
                    break;
                // 水平柱状图
                case "horiBar":
                    {
                        chartData = this.handleHoriBarData(ajaxData);
                    }
                    break;
                default: {
                    chartData = this.handleLineData(ajaxData);
                    break;
                }
            }
            return chartData;
        },
        // 处理折线图数据
        handleLineData(data) {
            console.log("折线图数据", data);
            let chartData = {};
            let xSet = new Set();
            let dealingData = [];
            let completeData = [];
            data.data.map((item) => {
                xSet.add(item.month);
                if (item.issue_status_text == "进行中") {
                    dealingData.push(item.quantity);
                } else {
                    completeData.push(item.quantity);
                }
            });
            chartData = {
                title: {
                    text: data.title,
                    left: "center",
                },
                legend: {
                    left: "center",
                    top: 25,
                    data: ["进行中", "已解决"],
                },
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
                    },
                },
                xAxis: {
                    type: "category",
                    data: Array.from(xSet),
                },
                yAxis: {
                    type: "value",
                },
                series: [
                    {
                        name: "进行中",
                        data: dealingData,
                        // areaStyle: {},
                        type: "line",
                    },
                    {
                        name: "已解决",
                        data: completeData,
                        // areaStyle: {},
                        type: "line",
                    },
                ],
            };
            return chartData;
        },
        // 饼图
        handlePieData(data) {
            console.log("饼图数据", data);
            let chartData = {};
            let pieNameSet = new Set();
            // 售前
            let data1 = [];
            // 售后
            let data2 = [];
            // 售中
            let data3 = [];
            data.data.map((item) => {
                pieNameSet.add(item.issue_type);
                if (item.issue_category_status_text == "售前") {
                    data1.push(item);
                } else if (item.issue_category_status_text == "售中") {
                    data2.push(item);
                } else {
                    data3.push(item);
                }
            });
            data1 = handleSetArray(pieNameSet, data1);
            data2 = handleSetArray(pieNameSet, data2);
            data3 = handleSetArray(pieNameSet, data3);
            function handleSetArray(set, data) {
                let result = [];
                for (let key of set.keys()) {
                    data.map((item) => {
                        if (item.issue_type == key) {
                            result.push({
                                value: item.quantity,
                                name: key,
                            });
                        }
                    });
                }
                return result;
            }
            function handleChartData(chartData) {
                return {
                    title: {
                        text: data.title,
                        left: "52%",
                    },
                    tooltip: {
                        trigger: "item",
                        formatter: "{a} <br/>{b} : {c} ({d}%)",
                    },
                    // legend: {
                    //     orient: "vertical",
                    //     left: "left",
                    //     data: Array.from(pieNameSet),
                    // },
                    series: [
                        {
                            name: "类型分布",
                            radius: "65%",
                            center: ["60%", "50%"],
                            data: chartData,
                            type: "pie",
                        },
                    ],
                };
            }
            chartData = handleChartData(data3);

            this.switchDataMap = [
                {
                    label: "售后",
                    chartData: handleChartData(data3),
                },
                {
                    label: "售前",
                    chartData: handleChartData(data1),
                },
                {
                    label: "售中",
                    chartData: handleChartData(data2),
                },
            ];
            console.log("饼图", chartData);
            return chartData;
        },
        // 堆叠柱状图
        handleStackBarData(data) {
            console.log("堆叠柱状图数据", data, this.stackLabelMap);
            let chartData = {};
            let channelSet = new Set();
            let statusSet = new Set();
            let resultData = [];
            data.data.map((item) => {
                channelSet.add(item[this.stackLabelMap.xLabel]);
                statusSet.add(item[this.stackLabelMap.yLabel]);
            });
            for (let statusName of statusSet.keys()) {
                let statusData = {
                    name: statusName,
                    type: "bar",
                    stack: "status",
                    data: [],
                };
                for (let channelName of channelSet.keys()) {
                    data.data.map((item) => {
                        if (
                            item[this.stackLabelMap.xLabel] == channelName &&
                            item[this.stackLabelMap.yLabel] == statusName
                        ) {
                            statusData.data.push(item.quantity);
                        }
                    });
                }
                resultData.push(statusData);
            }
            let channelArray = Array.from(channelSet);
            for (let i = 0; i < channelArray.length;) {
                let needFilter = true;
                for (let j = 0; j < resultData.length; j ++) {
                    if (resultData[j].data[i] != 0) {
                        needFilter = false;
                    }
                }
                if (needFilter) {
                    channelArray.splice(i, 1);
                    resultData.map(item => {
                        item.data.splice(i, 1);
                    });
                }
                else {
                    i ++
                }
            }

            console.log("堆叠", channelSet, resultData);
            chartData = {
                title: {
                    text: data.title,
                    left: "center",
                },
                legend: {
                    left: "center",
                    top: 25,
                    data: Array.from(statusSet),
                },
                tooltip: {
                    show: true,
                    trigger: "axis",
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
                    },
                    // formatter: (params) => {
                    //     console.log(params);
                    // },
                },
                dataZoom: [
                    {
                        type: "inside",
                    },
                    {
                        type: "slider",
                    },
                ],
                xAxis: {
                    type: "category",
                    data: channelArray,
                },
                yAxis: {
                    type: "value",
                },
                series: resultData,
            };
            return chartData;
        },
        // 水平柱状图
        handleHoriBarData(data) {
            console.log("水平柱状图数据", data);
            let chartData = {};
            let skuSet = new Set();
            let resultData = [];
            data.data.map((item) => {
                skuSet.add(item.seller_sku);
                resultData.push(item.quantity);
            });
            chartData = {
                title: {
                    text: data.title,
                    left: "center",
                },
                legend: {
                    left: "center",
                    top: 25,
                    data: ["进行中", "已解决"],
                },
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
                    },
                },
                xAxis: {
                    type: "value",
                },
                yAxis: {
                    type: "category",
                    data: Array.from(skuSet).reverse(),
                },
                series: [
                    {
                        data: resultData.reverse(),
                        type: "bar",
                    },
                ],
            };
            console.log("resultData", resultData);
            return chartData;
        },
    },
};
</script>